const api = require("../api.js");
const {login, isLogin} = require('../../../modules/auth-login');
//获取应用实例
const {network, auth, common} = getApp();

Page({
  data: {
    authFail: false,
    link: '',
    WithParams: false,
    optionsParams: {}
  },
  cutOff (str) {
    const a = str.split('&');
    const option = {};
    for (var i = 0; i < a.length; i++) {
      const o = a[i].split('=');
      option[o[0]] = o[1];
    }
    return option;
  },
  onLoad (options) {
    let scene = '';
    console.log(options.scene, '==========================================');
    if (options.scene) {
      scene = decodeURIComponent(options.scene);
    }
    let option = {};
    console.log(scene, 'scene==========================================');
    if (scene == '' || scene == undefined || scene == 'undefined') {
      option =  this.cutOff(scene);
    } else {
      wx.setStorageSync('withParams', true);
      wx.setStorageSync('parnerUrl', '?scene=' + scene);
      wx.removeStorageSync('token');
      wx.removeStorageSync('user');
      this.setData({
        WithParams: true
      });
    }
    this.setData({
      optionsParams: options
    });
    isLogin(this.dealFn);
  },
  routerJump (hasBirth, id) {
    const urlParam = this.data.urlParam;
    let link = '';
    console.log(urlParam, "urlParam");
    console.log(hasBirth, "hasBirth");
    console.log(id, "id");
    // 服务端推送
    /*
    if (urlParam.type) {
      if (urlParam.type == 1) {
        link = `/pages/home/detail/index?id=${urlParam.id || 0}`
      }
      wx.redirectTo({
        url: link
      });
    } else {
      // 来自祝福
      if (urlParam.blessId) {
        wx.showLoading({
          title: '加载中...',
        })
        network.get(api.getBlessList, {
          userPkid: urlParam.blessId,
          pageIndex: 1,
          pageSize: 1
        }).then(data => {
          wx.hideLoading();
          if (data.IsExistsMessage) {
            link = `/pages/home/main/index`
          } else {
            link = `/pages/edit/add-blessing/index?userName=${urlParam.userName}&userId=${urlParam.blessId}`;
          }
          wx.redirectTo({
            url: link
          });
        });
      } else if (urlParam.userId) {
        // 来自邀请，自己打开
        if (urlParam.userId == id) {
          link = `/pages/home/main/index`;
          wx.redirectTo({
            url: link
          });
        } else {
          // 来自邀请，别人打开
          // 填写过生日
          wx.showLoading({
            title: '加载中...',
          })
          network.get(api.getBlessList, {
            userPkid: urlParam.userId,
            pageIndex: 1,
            pageSize: 1
          }).then(data => {
            wx.hideLoading();
            if (data.UserInfo.IsFriend) {
              link = '/pages/home/main/index';
            } else {
              if (hasBirth) {
                link = `/pages/edit/my-birthday/index?friendId=${urlParam.userId}&id=${id}`;
              } else {
                // 没有填写生日
                link = `/pages/edit/my-birthday/index?friendId=${urlParam.userId}`;
              }
            }
            wx.redirectTo({
              url: link
            });
          });
        }
      } else {
        // if (hasBirth) {
        //   link = `/pages/home/main/index`;
        // } else {
        //   link = `/pages/edit/my-birthday/index`;
        // }
        link = `/pages/home/main/index`;
        wx.redirectTo({
          url: link
        });
      }
    }
    */
  },
  eventListener (res, state) {
    console.log(res, state, 'eventlistenrt - res auth-blank');
    if (state === 'compelte') {
      wx.showLoading({
        title: '授权中',
      })
      // isLogin(login, this.dealFn, res.userInfo.avatarUrl, res.userInfo.nickName);
      login(this.dealFn);
    } else {
      // 授权失败停留当前页面
      this.setData({authFail: true});
    }
  },
  dealFn (data, state) {
    console.log(data, '===============================');
    console.log(state, 'state===========================');
    // 自动登录失败，会调用授权逻辑来授权登录
    if (state === 'isLoginFail') {
      return auth.userInfo(this.eventListener);
    }
    // 授权登录成功
    if (state === 'login') {
      console.log('登录000000000000000000000000000000000000000000000000000000000');
      try {
        wx.setStorageSync('user', JSON.stringify(data));
        console.log(this.data.optionsParams, '绑定上线参数');
        if (this.data.optionsParams && this.data.optionsParams.u) {
          common.bindTop(this.data.optionsParams.u);
        }
      } catch (e) {
      }
      try {
        wx.setStorageSync('token', data.Token)
      } catch (e) {
      }
      wx.hideLoading();
      // 路由跳转
      if (this.data.WithParams) {
        wx.redirectTo({url: '/pages/home/main/index'});
      } else {
        wx.redirectTo({url: '/pages/home/main/index'});
      }
      return false;
    }
    // 自动登录成功
    if (state === 'isLogin') {
      try {
        wx.setStorageSync('user', JSON.stringify(data));
        console.log(this.data.optionsParams, '绑定上线参数');
        if (this.data.optionsParams && this.data.optionsParams.u) {
          common.bindTop(this.data.optionsParams.u);
        }
      } catch (e) {
      }
      // 路由跳转
      console.log(JSON.stringify(data), '返回信息');
      wx.redirectTo({url: '/pages/home/main/index'});
    } else {
      wx.hideLoading();
      wx.showToast({
        title: '授权失败',
        icon: 'none',
        duration: 1000
      })
      // 登录失败
      this.setData({authFail: true});
    }
  },
  // 重新授权
  reAuth () {
    auth.userInfo(this.eventListener);
  }
});
